home *** CD-ROM | disk | FTP | other *** search
- Path: access1.digex.net!not-for-mail
- From: ell@access1.digex.net (Ell)
- Newsgroups: comp.lang.c++
- Subject: Re: Overload of operator=
- Date: 18 Jan 1996 02:37:53 GMT
- Organization: The Universe
- Message-ID: <4dkbq1$mni@news4.digex.net>
- References: <30FBCAA1.34A7@novell.com>
- NNTP-Posting-Host: access1.digex.net
- X-Newsreader: TIN [UNIX 1.3 950824BETA PL0]
-
- Greg Johnson (gregjo@novell.com) wrote:
- : I want to overload the assignment operator, for some debugging purposes.
- : But after I overload the operator, somehow, I need to perform the
- : default assignment. How do I do that if I don't know the exact size
- : of the source or destination?
- : How do I avoid recursion and perform the default behavior?
- : For example:
- :
- : class BaseObj {
- : public:
- : long x;
- : BaseObj& operator=(BaseObj&);
- : BaseObj(void) : x(0) {};
- : };
- :
- : BaseObj& BaseObj::operator=(BaseObj & ptr)
- : {
- : *this = ptr; // this will recursively call operator=
-
- This above line only takes effect if the left hand side is a BaseObj.
- Generally, the assignment operator only needs to be defined when a class
- has heap based data members. Generally you do not want to simply assign
- the right hand side (rhs) to the left hand side (lhs) when you need to
- have an assignment operator. Try the following:
-
- BaseObj& operator=(BaseObj& ref)
- {
- if (this != &ref)
- {
- x = ref.long; // does not call the above overload of '='
- } // because the left hand side (lhs) is a 'long'
- // not a BaseObj class. so no recursion.
- return *this;
- }
-
- Elliott
-